package com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.api;

import cn.hutool.json.JSONUtil;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.dto.PPTProgressResponse;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.util.ApiAuthAlgorithm;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * PPT进度查询API
 * 调用讯飞开放平台查询PPT生成进度
 */
@Slf4j
@Component
public class PPTProgressChecker {

    @Value("${xunfei.api.ppt.progress-url:https://zwapi.xfyun.cn/api/ppt/v2/progress}")
    private String progressUrl;

    @Value("${xunfei.api.ppt.app-id}")
    private String appId;

    @Value("${xunfei.api.ppt.api-key}")
    private String apiKey;

    private final static OkHttpClient client = new OkHttpClient().newBuilder()
            .connectionPool(new ConnectionPool(100, 5, TimeUnit.MINUTES))
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    /**
     * 查询PPT生成进度
     *
     * @param sid 请求唯一ID
     * @return 进度查询响应
     */
    public PPTProgressResponse checkProgress(String sid) {
        try {
            log.info("开始查询PPT生成进度，SID: {}", sid);
            
            if (sid == null || sid.trim().isEmpty()) {
                return buildErrorResponse("SID不能为空");
            }
            
            // 获取时间戳和签名
            long timestamp = System.currentTimeMillis()/1000;
            String ts = String.valueOf(timestamp);

            ApiAuthAlgorithm auth = new ApiAuthAlgorithm();
            String signature = auth.getSignature(appId, apiKey, timestamp);
            
            // 构建请求URL
            HttpUrl.Builder urlBuilder = HttpUrl.parse(progressUrl).newBuilder();
            urlBuilder.addQueryParameter("sid", sid);
            
            // 构建请求
            Request httpRequest = new Request.Builder()
                    .url(urlBuilder.build())
                    .addHeader("appId", appId)
                    .addHeader("timestamp", ts)
                    .addHeader("signature", signature)
                    .get()
                    .build();
            
            // 发送请求
            try (Response response = client.newCall(httpRequest).execute()) {
                String responseBody = response.body().string();
                log.info("PPT进度查询结果: {}", responseBody);
                
                // 解析响应
                if (response.isSuccessful()) {
                    return JSONUtil.toBean(responseBody, PPTProgressResponse.class);
                } else {
                    log.error("PPT进度查询失败，状态码: {}, 响应: {}", response.code(), responseBody);
                    return buildErrorResponse("请求失败: " + response.code() + ", " + responseBody);
                }
            }
        } catch (Exception e) {
            log.error("PPT进度查询异常", e);
            return buildErrorResponse("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 构建错误响应
     */
    private PPTProgressResponse buildErrorResponse(String message) {
        PPTProgressResponse errorResponse = new PPTProgressResponse();
        errorResponse.setFlag(false);
        errorResponse.setCode(-1);
        errorResponse.setDesc(message);
        return errorResponse;
    }
} 